package com.dsh.service;

import com.dsh.feign.GoodsBrowserLogFeignClient;
import com.dsh.model.GoodsBrowserLog;
import com.dsh.model.GoodsBrowserLogEntity;
import com.rabbitmq.client.Channel;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class GoodsBrowserLogListener {
    @Autowired
    RestHighLevelClient restHighLevelClient;
    @Value("${guli.elasticsearch.index}")
    String index;
    @Autowired
    RedisTemplate redisTemplate;
    @Qualifier("com.dsh.feign.GoodsBrowserLogFeignClient")
    @Autowired
    GoodsBrowserLogFeignClient goodsBrowserLogFeignClient;

    @Scheduled(cron = "0/10 * * * * ?")
    public void addGoodsBrowserLog() throws IOException {
        String lastTime = (String) redisTemplate.opsForValue().get("lastTime");
        Map map=new HashMap();
        if (lastTime!=null){
            map.put("lastTime",lastTime);
        }
        List<GoodsBrowserLogEntity> goodsBrowserLogList = goodsBrowserLogFeignClient.findGoodsBrowserLog(map);
        for (GoodsBrowserLogEntity logEntity : goodsBrowserLogList) {
            saveToEs(logEntity);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        redisTemplate.opsForValue().set("lastTime",sdf.format(new Date()));

    }

    private void saveToEs(GoodsBrowserLogEntity browserLog) throws IOException {
        Map map=new HashMap();
        map.put("user_name",browserLog.getUserName());
        map.put("goods_id",browserLog.getGoodsId());
        map.put("user_name",browserLog.getUserName());
        map.put("name",browserLog.getName());
        map.put("catalog_name",browserLog.getCatalogName());
        map.put("user_name",browserLog.getUserName());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        map.put("log_time", sdf.format(browserLog.getLogTime()));

        IndexRequest indexRequest = new IndexRequest(index);
        indexRequest.source(map);
        restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
    }
}
